"""
@author: 方杰
@file: 猜拳游戏-test.py
@time: 2023/4/16 21:36
"""

import random

class User():
    def __init__(self, user_id, beans):
        self.beans = int(beans)
        self.user_id = user_id
        self.room = None

    def join_room(self, room):
        if len(room.player) < 2:
            room.player.append(self)  # 将用户加入房间
            print(f"{self.user_id}加入了房间{room.room_id}")
        else:
            print("房间已满")

    def exit_room(self):
        self.room.player.remove(self)  # 将用户从房间中移除
        self.room = None

    def play(self):
        input("请按任意键开始猜拳:")
        guess = random.randint(1, 3)  # 随机出拳  1表示剪刀  2表示石头  3代表布
        print(f"{self.user_id}出拳为：{guess}")
        return guess

class Room():
    def __init__(self, room_id):
        self.room_id = room_id
        self.player = []

    def start_game(self):
        if len(self.player) == 2:  # 如果房间里有两个人
            while True:
                guess1 = self.player[0].play()  # 玩家1出拳
                if guess1 == 'q':
                    return
                guess2 = self.player[1].play()  # 玩家2出拳
                result = self.judge(guess1, guess2)  # 判断胜负
                if result == 0:  # 平局
                    print("平局")
                elif result == 1:  # 玩家1获胜
                    print(f"{self.player[0].user_id}获胜")
                    self.player[0].beans += 100
                    self.player[1].beans -= 100
                else:  # 玩家2获胜
                    print(f"{self.player[1].user_id}获胜")
                    self.player[0].beans -= 100
                    self.player[1].beans += 100
                if self.player[0].beans <= 0:
                    print(f"{self.player[0].user_id}金豆不足，游戏结束")
                    return
                elif self.player[1].beans <= 0:
                    print(f"{self.player[1].user_id}金豆不足，游戏结束")
                    return
        else:
            print("人数不足，无法开始游戏")

    def judge(self, guess1, guess2):
        if guess1 == guess2:  # 平局
            return 0
        elif guess1 - guess2 == -1 or guess1 - guess2 == 2:  # 玩家1获胜
            return 1
        else:  # 玩家2获胜
            return -1


print("欢迎进入猜拳游戏".center(40, "*"))
players = []
while len(players) < 2:
    user_id, beans = input("请输入需要注册的账号、初始金豆（空格分隔）：").split()
    player = User(user_id, beans)
    players.append(player)

room_id = input("请输入房间ID：")
room = Room(room_id)
for player in players:
    player.join_room(room)

while True:
    choice = input("请选择：1.开始游戏 2.退出游戏(q)\n")
    if choice == "1":
        room.start_game()
    elif choice == "2":
        for player in players:
            player.exit_room()
        break
    else:
        print("输入错误，请重新选择！")

